package com.java.advance.custom.mybatis.session;


import com.java.advance.custom.mybatis.config.Configuration;
import com.java.advance.custom.mybatis.config.MapperStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Properties;

/**
 * 1、初始化配置信息
 * 2、生成SqlSession
 * <p>
 * Created by aivin on 2019/3/6.
 */
public class SqlSessionFactory {

    private Configuration conf = new Configuration();

    private final static String DB_CONFIG_FILE = "";
    private final static String MAPPER_CONFIG_LOCATION = "";

    public SqlSessionFactory() {
        loadDbInfo();
        loadMappersInfo();
    }

    //加载数据库配置信息
    private void loadDbInfo() {
        //加载数据库配置文件
        InputStream daIn = this.getClass().getClassLoader().getResourceAsStream("");
        Properties properties = new Properties();
        try {
            properties.load(daIn);
        } catch (IOException e) {
            e.printStackTrace();
        }
        conf.setJdbcDriver(properties.get("jdbc.driver").toString());
        conf.setJdbcUrl(properties.get("jdbc.url").toString());
        conf.setJdbcUsername(properties.get("jdbc.username").toString());
        conf.setJdbcPassward(properties.get("jdbc.password").toString());
    }

    // 加载指定文件夹下的所有的mapper.xml映射文件
    private void loadMappersInfo() {
        URL resources = null;
        resources = this.getClass().getClassLoader().getResource(MAPPER_CONFIG_LOCATION);
        File mappers = new File(resources.getFile());
        if (mappers.isDirectory()) {
            File[] files = mappers.listFiles();
            // 遍历文件夹下所有的mapper.xml映射文件，解析信息后，注册到conf对象中
            if (files != null && files.length > 0) {
                for (File file : files) {
                    loadMapperInfo(file);
                }
            }
        }

    }

    //加载指定的mapper.xml文件
    private void loadMapperInfo(File file) {
        // 创建saxReader对象
        SAXReader reader = new SAXReader();
        // 通过read方法读取一个文件转换成Document对象
        Document document = null;
        try {
            document = reader.read(file);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        //获取跟节点元素对象<mapper>
        Element rootElement = document.getRootElement();
        //获取命名空间
        String namespace = rootElement.attribute("name").getData().toString();
        //获取select子节点列表
        List<Element> selects = rootElement.elements("select");
        if (selects != null && selects.size() > 0) {
            for (Element element : selects) {
                MapperStatement mapperStatement = new MapperStatement();
                String id = element.attribute("id").getData().toString();
                String resultType = element.attribute("resultType").getData().toString();
                String sql = element.getData().toString();
                String sourceId = namespace + "." + id;
                //给mapperStatement属性赋值
                mapperStatement.setSourceId(sourceId);
                mapperStatement.setResultType(resultType);
                mapperStatement.setSql(sql);
                mapperStatement.setNamespace(namespace);
                //注册到conf对象中
                conf.getMapperStatements().put(sourceId, mapperStatement);
            }
        }

    }

    public SqlSession openSession() {
        return new DefaultSqlSession(conf);
    }


}
